package com.suning.sawp.service.impl.vguide;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.suning.framework.page.QueryResult;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.MyQueryParam;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.intf.vguide.VGuideService;
import com.suning.sawp.po.vguide.VGuideRecord;

/**
 * 
 * V导购业务逻辑类<br>
 * 〈功能详细描述〉
 *
 * @author Wuxiao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class VGuideServiceImpl implements VGuideService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(VGuideServiceImpl.class);

	@Resource
	MongoTemplate safeMongoTemplate;

	@SuppressWarnings("rawtypes")
	@Override
	public ReturnMsg addGuideRecord(String telNo, String userId,
			String storeCode) {
		ReturnMsg ret = new ReturnMsg();
		if (StringUtils.isBlank(telNo) || StringUtils.isBlank(userId)) {
			ret.setRetFlag(ReturnMsg.FAIL);
			ret.setErrorCode(ErrorCodeConstants.VGUIDE_ERR_E001);
			ret.setErrorMessage(ErrorCodeConstants.VGUIDE_ERR_MAP
					.get(ErrorCodeConstants.VGUIDE_ERR_E001));
			return ret;
		}
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
		VGuideRecord record = new VGuideRecord();
		record.setCreateTime(new Date());
		record.setOaAccountNo(userId);
		record.setRecordDate(sd.format(new Date()));
		record.setStoreCode(storeCode);
		record.setTelNo(telNo);
		try {
			safeMongoTemplate.save(record);
			ret.setRetFlag(ReturnMsg.SUCCESS);
		} catch (DuplicateKeyException e) {
		    LOGGER.error("VGuideService.addGuideRecord DuplicateKeyException error", e);
			ret.setRetFlag(ReturnMsg.FAIL);
			ret.setErrorCode(ErrorCodeConstants.VGUIDE_ERR_E002);
			ret.setErrorMessage(ErrorCodeConstants.VGUIDE_ERR_MAP
					.get(ErrorCodeConstants.VGUIDE_ERR_E002));
		}
		return ret;
	}

	@Override
	public QueryResult<VGuideRecord> queryGuideRecordList(
			MyQueryParam<String> queryParam) {

		// 获取业务请求参数
		String userId = queryParam.getQueryParam();

		LOGGER.debug("queryGuideRecordList,userId=" + userId + ", pageSize="
				+ queryParam.getCurrIndex() + ", currIndex="
				+ queryParam.getCurrIndex());

		if (StringUtils.isEmpty(userId)) {
			LOGGER.warn("userId is empty");
			return null;
		}

		// 初始化db查询参数
		Query query = new Query();
		Criteria criteria = Criteria.where("oaAccountNo").is(userId);
		
		query.addCriteria(criteria).with(new Sort(Direction.DESC, "createTime"));

		// 设置分页参数
		query.skip(queryParam.getCurrIndex());// skip相当于从那条记录开始
		query.limit(queryParam.getPageSize());// 从skip开始,取多少条记录

		// 访问db
		List<VGuideRecord> recordList = safeMongoTemplate.find(query,
				VGuideRecord.class);

		// 初始化返回对象
		QueryResult<VGuideRecord> result = new QueryResult<VGuideRecord>();
		result.setPageSize(queryParam.getPageSize());

		// 设置当前页数据列表
		result.setDatas(recordList);

		return result;
	}
}
